<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="800"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <yt-crud
        v-bind="options"
        ref="crudRef"
        @onLoad="getData"
        :fun-props="{
          exportBtn: false,
          delBtn: false,
          addBtn: false,
          hide: true,
        }"
        :table-props="{
          selection: false,
          delBtn: false,
          pageHide: true,
          viewBtn: false,
          editBtn: false,
          menuSlot: true,

        }"
        :form-props="{
          loading: state.form.loading,
          width: 500,
        }"
        :loading="state.loading"
        :total="state.total"
        v-model:page="state.page"
        v-model:query="state.query"
        @delFun="handleDelete"
        @saveFun="onSave"
        @openBeforeFun="openBeforeFun"
        @change="onChange"
      >
        <template #menuSlot="scope:any">
          <div class="menu-btn" v-has-permi="['business:charger:edit']">
            <el-tooltip class="box-item" effect="dark" :content="t('business.charger.gun.action.bindParking')" placement="top">
              <el-button link type="primary" class="iconfont icon-tingchechangguanli2" @click="handleBindParking(scope.row)" />
            </el-tooltip>
          </div>
        </template>

        <template #speed="scope:any">
          <DictTag :options="ChargerGunSpeedEnum" :value="scope.row.speed" />
        </template>
        <template #current="scope:any">
          <DictTag :options="ChargerGunCurrentEnum" :value="scope.row.current" />
        </template>
        <template #power="scope:any"> {{scope.row.power}}KW </template>
      </yt-crud>
    </div>
    <template #footer>
      <el-button @click="handleClose" :loading="state.loading">{{t('crud.closeText')}}</el-button>
    </template>

    <ChargerGunBindParking ref="bindParkingRef" @success="handleSuccess" />
  </el-dialog>
</template>

<script lang="ts" setup>

import YtCrud from '@/components/common/yt-crud.vue'
import {IColumn} from '@/components/common/types/tableCommon'
import {chargerGunList, chargerGunDelete, chargerGunBatchDelete, chargerGunSave } from '@/api/business/chargerGun'
import {useI18n} from 'vue-i18n'

import ChargerGunBindParking from '@/views/business/charger/modules/ChargerGunBindParking.vue'
import {optionSelect as parkingOptionSelect} from '@/api/business/stationParking'
import {ComponentInternalInstance} from 'vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { ChargerGunSpeedEnum, ChargerGunCurrentEnum } = toRefs<any>(proxy?.useEnum('charger_gun_speed_enum', 'charger_gun_current_enum'))
const { t } = useI18n()


const bindParkingRef = ref()

const state = reactive({
  visible: false,
  loading: false,
  recharge: {},
  form: {
    loading: false,
  },
  title: t('business.charger.action.chargerGunList'),
  page: {
    pageSize: 30,
    pageNum: 1,
  },
  total: 0,
  query: {},
})

const charger = ref<any>({})
const parkings = ref<any[]>([])

const column = ref<IColumn[]>([
  {
    label: t('business.charger.gun.no'),
    key: 'no',
    search: false,
    formHide: false,
    slot: false,
  },
  {
    label: t('business.charger.gun.speed'),
    key: 'speed',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.charger.gun.current'),
    key: 'current',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.charger.gun.power'),
    key: 'power',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.charger.gun.parkingId'),
    key: 'parkingId',
    type: 'i18nSelect',
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      option: [],
    },
    search: false,
    formHide: false,
    slot: false,
  },

])

const openDialog = (row?: any) => {
  charger.value = row
  state.visible = true
}

const handleClose = () => {
  state.visible = false
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})

const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  chargerGunList({
    ...state.page,
    ...state.query,
    ...{ chargerId: charger.value.id}
  })
  .then((res) => {
    data.value = res.data.rows
    state.total = res.data.total
  })
  .finally(() => {
    state.loading = false
  })

  parkingOptionSelect({
    stationId: charger.value.stationId
  }).then((res) => {
    parkings.value = res.data || []

    column.value.forEach((item) => {
      if (item.key === 'parkingId') {
        item.componentProps.options = parkings.value
      }
    })
  })
}

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  await chargerGunSave(toRaw(data))
  state.loading = false
  ElMessage.success(t('operate.tooltip.success'))
  cancel()
  getData()
}

const handleBindParking = (row: any) => {
  bindParkingRef.value.openDialog(parkings.value, row, charger.value)
}

const handleSuccess = () => {
  getData()
}

// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    data.chargerId = charger.value.id
  } else if (type === 'update') { /* empty */ }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    await chargerGunBatchDelete(row.map((m) => m.id))
  } else {
    await chargerGunDelete(row.id)
  }
  ElMessage.success(t('operate.tooltip.success'))
  state.loading = false
  getData()
}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>
